﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using DevExpress.XtraEditors;

namespace NHTClient
{
    public partial class NHTServerList : XtraForm
    {
        private const Int16 lastestServer = 16;
        private static Int16 ServerNumber { get; set; }
        private NHTMain mainForm;
        public Int16 Data
        {
            get { return Convert.ToInt16(txtServerNumber.Text); }
            set { txtServerNumber.Text = value.ToString(); }
        }

        public NHTServerList(NHTMain frm)
        {
            InitializeComponent();
            mainForm = frm;
        }

        /// <summary>
        /// Check input text string is valid or not
        /// </summary>
        /// <param name="_control"></param>
        /// <returns>Server out of range or not</returns>
        private Boolean ServerOutOfRange(TextEdit _control)
        {
            bool isValid = false;
            Int16 inputServerNumber = 0;

            if (!String.IsNullOrEmpty(_control.Text))
            {
                inputServerNumber = Convert.ToInt16(_control.Text);

                if (inputServerNumber <= lastestServer)
                {
                    ServerNumber = inputServerNumber;
                    isValid = true;
                }
            }
            else { isValid = false; }

            return isValid;
        }

        /// <summary>
        /// Synchronize data between forms
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">EventArgs</param>
        private void btnStartGame_Click(object sender, EventArgs e)
        {
            if (ServerOutOfRange(txtServerNumber))
            {
                OnDataAvailable(null);
                mainForm.NewLogin(ServerNumber);
                this.Close();
            }
            else
            {
                dxErrorProvider.SetError(txtServerNumber,
                    String.Format("Server mới nhất là: {0}\r\nXin vui lòng nhập vào một số nhỏ hơn hoặc tương đương với server mới nhất.", lastestServer));
            }
        }

        /// <summary>
        /// Event to indicate new data is available
        /// </summary>
        public event EventHandler DataAvailable;
        /// <summary>
        /// Called to signal to subscribers that new data is available
        /// </summary>
        /// <param name="e">EventArgs</param>
        protected virtual void OnDataAvailable(EventArgs e)
        {
            EventHandler eh = DataAvailable;
            if (eh != null)
            {
                eh(this, e);
            }
        }
    }
}